/**
 * 
 * 
 * @param latitude
 * @param longitude
 * @param address
 */
function doOnLoad(latitude, longitude, gridId, address) {
	loadWeather(latitude, longitude, gridId, address);
	updateSubstance(latitude, longitude, gridId, address);
}

function updateSubstance(lat, lng, gridId, address) {
	$.ajax({
		type : "GET",
		url : "data/currentsensor",
		dataType : "json",
		data : {
			current : true,
			latitude : lat,
			longitude : lng,
			gridId : gridId
		}
	}).done(function(json) {
		updatePollutionData(json);
	});
}

function loadWeather(lat, lng) {
	var url = 'http://api.wunderground.com/api/3b4c284cf1faa2dd/conditions/q/'
			+ lat + "," + lng + '.json';
	$.ajax({
		type : "GET",
		url : url,
		dataType : "jsonp"
	}).done(function(json) {
		updateWeather(json);
	});
}

function updateWeather(json) {
	var o = json.current_observation;
	$("#curIcon img").attr("src", o.icon_url);
	$("#curCond span").html(o.weather);
	$("#curTemp .wx-value").html(o.temp_c);
	$("#curFeel .wx-value").html(o.feelslike_c);
	// $("#curWind").html("Wind: " + o.wind_string);
	$("#curHumidity .wx-value").html(o.relative_humidity);

}

function updatePollutionData(json) {
	var substance_list = [ "no2", "pm10", "so2", "o3", "pm2p5" ];
	for (var i = 0; i < substance_list.length; i++) {
		updateSubstanceInfo(substance_list[i], json);
	}
	var atRisk = true;
	var banding = Pollution.getAirQualityBanding(Pollution.getAQI(json));
	var messages = Pollution.getHealthMessage(banding, atRisk);
	var pollutionClass = Pollution.getAirQualityClass(json);
	$("#health-message").html("<p>" + messages[0] + "</p>").addClass(
			pollutionClass);
	if (messages[1]) {
		$("#health-message-note").append(messages[1]);
	}

	$("#air-quality-indicator").find(".dark-" + pollutionClass).append(
			"<span id='circle'></span>");
}

function updateSubstanceInfo(name, json) {
	var val = Math.round(json[name] * 100) / 100;// making it two decimal
	// places
	var className = Pollution.getPollutionClass(val, name);
	var polLevel = Pollution.getPollutionLevel(val, name);
	$("#" + name).find(".aq-indicator, .reading").addClass(className);
	$("#" + name + " .reading.badge").html(
			val + "<sub>&mu;g/m<sup>3</sup></sub>");
	$("#" + name + " .aq-indicator.badge").html(polLevel + 1);
	// $("#" + name + " .aq-indicator.badge").html(className.substring(0,
	// className.indexOf("-")));
}
